import cv2
import numpy as np

from moviepy.editor import VideoFileClip, CompositeVideoClip

# 视频和图片的路径
video_path = 'd:\\pdf\\a1.mp4'
image_path = 'd:\\pdf\\a2.png'
output_path = 'd:\\pdf\\a3.mp4'

# 读取视频和图片
cap = cv2.VideoCapture(video_path)
image = cv2.imread(image_path)

#  获取原始视频的高度与宽度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 设置图片添加到视频的时间点（单位：秒）
time_to_add_image = 5  # 例如，图片将在视频的第5秒出现

# 获取视频的编解码器
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# 创建一个视频写入对象
out = cv2.VideoWriter(output_path, fourcc, 30.0, (frame_width, frame_height), isColor=True)

# video_clip = VideoFileClip(video_path).set_duration(23)  # 设置视频时长为5秒
# audio_clip = video_clip.audio  # 提取原视频的音频


# 读取视频的每一帧
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    # 计算当前帧是否超过设定的添加图片的时间点
    if cap.get(cv2.CAP_PROP_POS_MSEC) / 1000 >= time_to_add_image:
        # 调整图片的大小以匹配视频帧的大小
        resized_image = cv2.resize(image, (544, 544), interpolation=cv2.INTER_AREA)

        # 确定图片在帧上的位置
        x, y = 0, 200  # 示例位置，根据需要调整
        frame[y:y + resized_image.shape[0], x:x + resized_image.shape[1]] = resized_image

    # 将帧写入输出视频
    out.write(frame)

    # 显示帧（可选）
    cv2.imshow('Video', frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break


# video_clip2 = VideoFileClip(output_path).set_duration(23)  # 设置视频时长为5秒
# final_clip = CompositeVideoClip([video_clip2.set_pos((0, 0)), audio_clip])  # 将视频和音频组合
# final_clip.write_videofile("edited_video.mp4", codec='libx264', audio_codec='aac')  # 导出编辑后的视频


# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()


